package org.opensuse.bs.ui;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

import org.eclipse.core.resources.ISaveContext;
import org.eclipse.core.resources.ISaveParticipant;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;

public class BSWorkspaceSaveParticipant implements ISaveParticipant {

	public void doneSaving(ISaveContext context) {
		BSUIPlugin plugin = BSUIPlugin.getDefault();
       // delete the old saved state since it is not necessary anymore
       int previousSaveNumber = context.getPreviousSaveNumber();
       String oldFileName = "save-" + Integer.toString(previousSaveNumber);
       File f = plugin.getStateLocation().append(oldFileName).toFile();
       f.delete();
	}
	
	public void prepareToSave(ISaveContext context) throws CoreException {}

	public void rollback(ISaveContext context) {
		BSUIPlugin plugin = BSUIPlugin.getDefault();
       // since the save operation has failed, delete the saved state we have just written
       int saveNumber = context.getSaveNumber();
       String saveFileName = "save-" + Integer.toString(saveNumber);
       File f = plugin.getStateLocation().append(saveFileName).toFile();
       f.delete();
	}

	public void saving(ISaveContext context) throws CoreException {
		switch(context.getKind()) {
		case ISaveContext.FULL_SAVE:
			BSUIPlugin plugin = BSUIPlugin.getDefault();
			int saveNumber = context.getSaveNumber();
			String saveFileName = "save-" + Integer.toString(saveNumber);
			File f = plugin.getStateLocation().append(saveFileName).toFile();
            // if we fail to write, an exception is thrown and we do not update the path
			try {
				FileWriter out = new FileWriter(f);
				BufferedWriter output = new BufferedWriter(out);
				Vector<String> prjs = plugin.getAimed();
				for(String pn : prjs) {
					output.write(pn);
					output.newLine();
				}
				output.close();
			}catch(IOException e) {
				e.printStackTrace();
			}
			context.map(new Path("save"), new Path(saveFileName));
			context.needSaveNumber();
			break;
		case ISaveContext.PROJECT_SAVE:
			//IProject project = context.getProject();
			break;
		case ISaveContext.SNAPSHOT:
			break;
		}
	}

}
